package io.renren.service.impl;

import io.renren.service.MapService;
import org.springframework.stereotype.Service;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

@Service("mapService")
public class MapServiceImpl implements MapService {
    final static HostnameVerifier DO_NOT_VERIFY = (hostname, session) -> true;

    @Override
    public String searchStartEnd(String start, String end) throws NoSuchAlgorithmException, KeyManagementException, IOException {
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }

            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }
        }};

        URL url = new URL(String.format("https://map.bjsubway.com/api/searchstartend?start=%s&end=%s", start, end));

        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        conn.setHostnameVerifier(DO_NOT_VERIFY);
        conn.setRequestMethod("GET");

        conn.connect();
        int code = conn.getResponseCode();

        if (code == HttpsURLConnection.HTTP_OK) {
            InputStream is = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
                result.append('\r');
            }
            reader.close();
            return result.toString();
        }

        return "";
    }
}
